<?php
namespace App\Admin\Services;

use App\Models\AdminUser;
use App\Models\DyBaseInfo;
use Dcat\Admin\Admin;

class DyBaseInfosService
{
    public function getTimeLine($sfz)
    {
        $timelines = [];
        $base_info = $this->getBaseQuery(\App\Models\DyBaseInfo::class, $sfz)->select('jrsj', 'zrzssj')->first();
        if ($base_info && $base_info->jrsj) {
            array_push($timelines, [
                'sj' => $base_info->jrsj,
                'desc' => "加入党组织"
            ]);
        }
        if ($base_info && $base_info->zrzssj) {
            array_push($timelines, [
                'sj' => $base_info->zrzssj,
                'desc' => "转为正式党员"
            ]);
        }
        $qc = $this->getBaseQuery(\App\Models\DyQc::class, $sfz)->select('yszdw', 'qwdw', 'qcsj')->first();
        if ($qc && $qc->qcsj) {
            array_push($timelines, [
                'sj' => $qc->qcsj,
                'desc' => "从{$qc->yszdw}迁往{$qc->qwdw}"
            ]);
        }
        $qr = $this->getBaseQuery(\App\Models\DyQr::class, $sfz)->select('qrdw', 'yszdw', 'qrsj')->first();
        if ($qr && $qr->qrsj) {
            array_push($timelines, [
                'sj' => $qr->qrsj,
                'desc' => "从{$qr->yszdw}迁入{$qc->qrdw}"
            ]);
        }
        $fzdx = $this->getBaseQuery(\App\Models\DyFzdx::class, $sfz)->select('jrsj')->first();
        if ($fzdx && $fzdx->jrsj) {
            array_push($timelines, [
                'sj' => $fzdx->jrsj,
                'desc' => "确定发展对象"
            ]);
        }
        $jjfz = $this->getBaseQuery(\App\Models\DyJjfz::class, $sfz)->select('jrsj')->first();
        if ($jjfz && $jjfz->jrsj) {
            array_push($timelines, [
                'sj' => $jjfz->jrsj,
                'desc' => "确定入党积极分子"
            ]);
        }
        $timelines = collect($timelines)->sortBy('sj')->all();
        return $timelines;
    }

    private function getBaseQuery($model, $sfz)
    {
        $admin_user = AdminUser::find(Admin::user()->id);
        $query =  $model::query()->where('sfz', $sfz);
        if ($admin_user->isSuperManger()) {
            $query->where('is_main', 1);
        } else {
            $query->where('dwdm', $admin_user->dwdm);
        }
        return $query;
    }
}